//
//  KLoginViewController.m
//  TimeToCoin
//
//  Created by 8-PC on 2018/8/2.
//  Copyright © 2018年 QuanLi Technology Limited. All rights reserved.
//
#import "AppDelegate+AppService.h"

#import "KLoginViewController.h"
#import "NetworkSingleton.h"
#import "BaseModel.h"

#import "KUserLoginModel.h"
#import "KWXLoginUserListModel.h"
#import "KHomePageViewController.h"
#import "KMenuRootViewController.h"

@interface KLoginViewController ()<UITextFieldDelegate,UIAlertViewDelegate>
// icon 居中显示图
@property (nonatomic, strong)UIImageView *iconImageView;
// 账号输入
@property (nonatomic, strong)UITextField *userInputMessage;
// 账号输入cell布局
@property (nonatomic, strong)UIImageView *userNamebgView;// 密码输入
@property (nonatomic, strong)UITextField *passwordInputMessage;
// 密码cell布局
@property (nonatomic, strong)UIImageView *passwordbgView;
// 登录按钮
@property (nonatomic, strong)UIButton *loginButton;
// line1
@property (nonatomic, strong)UIView *line1;
// or
@property (nonatomic, strong)UILabel *orAppLoginLabel;
// line2
@property (nonatomic, strong)UIView *line2;
// 第三方登录按钮 —— 微信
@property (nonatomic, strong)UIButton *WechatLoginBtn;
@end

@implementation KLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setupUI];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShowChangeFrame:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideChangeFrame:) name:UIKeyboardWillHideNotification object:nil];
    //跳转到主界面
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wechatDidLoginNotification:) name:@"wechatDidLoginNotification" object:nil];
    
    [self.loginButton addTarget:self action:@selector(loginClick:) forControlEvents:UIControlEventTouchUpInside];

    
}

-(void)setupUI{
    [self.view addSubview:self.iconImageView];
    
    [self.view addSubview:self.userNamebgView];
    [self.view addSubview:self.userInputMessage];
    
    [self.view addSubview:self.passwordbgView];
    [self.view addSubview:self.passwordInputMessage];
    
    [self.view addSubview:self.loginButton];
    [self.view addSubview:self.line1];
    [self.view addSubview:self.orAppLoginLabel];
    [self.view addSubview:self.line2];
    [self.view addSubview:self.WechatLoginBtn];
    
    [self.iconImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).mas_offset(81);
        make.centerX.equalTo(self.view);
    }];
    
    [self.userNamebgView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.iconImageView.mas_bottom).mas_offset(30);
        make.centerX.equalTo(self.view);
        make.width.mas_equalTo(299);
        make.height.mas_equalTo(79);
    }];
    
    [self.userInputMessage mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.userNamebgView).mas_offset(-4);
        make.left.equalTo(self.userNamebgView).mas_offset(81);
        make.width.mas_equalTo(172);
        make.height.mas_equalTo(30);
    }];
    
    [self.passwordbgView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.userNamebgView.mas_bottom).mas_equalTo(-10);
        make.centerX.equalTo(self.view);
        make.width.mas_equalTo(299);
        make.height.mas_equalTo(79);
    }];
    
    [self.passwordInputMessage mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.passwordbgView).mas_offset(-4);
        make.left.equalTo(self.passwordbgView).mas_offset(81);
        make.width.mas_equalTo(172);
        make.height.mas_equalTo(30);
    }];
    
    [self.loginButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.passwordbgView.mas_bottom).mas_equalTo(-10);
        make.centerX.equalTo(self.view);
        make.width.mas_equalTo(299);
        make.height.mas_equalTo(79);
    }];
    
    [self.orAppLoginLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.loginButton.mas_bottom).mas_offset(10);
        make.centerX.equalTo(self.view);
    }];
    
    [self.line1 mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.orAppLoginLabel);
        make.right.equalTo(self.orAppLoginLabel.mas_left).mas_offset(-7);
        make.width.mas_equalTo(99);
        make.height.mas_equalTo(1);
    }];
    
    [self.line2 mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.orAppLoginLabel);
        make.left.equalTo(self.orAppLoginLabel.mas_right).mas_offset(7);
        make.width.mas_equalTo(99);
        make.height.mas_equalTo(1);
    }];
    
    [self.WechatLoginBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.orAppLoginLabel.mas_bottom).mas_offset(7);
        make.centerX.equalTo(self.view);
        make.width.mas_equalTo(299);
        make.height.mas_equalTo(79);
    }];
    
}

#pragma mark - 功能方法实现 -- 登陆按钮的点击方法
//登陆按钮的点击方法
- (void)loginClick:(NSDictionary*)params
{
    NSLog(@"账号登陆");
    if (self.userInputMessage.text.length == 0) {
        [SVProgressHUD showInfoWithStatus:@"亲,请输入注册手机号码"];
        [SVProgressHUD dismissWithDelay:1];
        return;
    }
    else if (self.passwordInputMessage.text.length == 0) {
        [SVProgressHUD showInfoWithStatus:@"请输入密码"];
        [SVProgressHUD dismissWithDelay:1];
        return;
    }

    [SVProgressHUD show];
    NSDictionary *parameters = @{
                                 @"_appid" : @"103",
                                 @"UserName" : self.userInputMessage.text,
                                 @"Password": self.passwordInputMessage.text
                                 };
    
    [[NetworkSingleton sharedManager]POSTdata:parameters Path:@"common/user/login" successBlock:^(id responseBody) {

        BaseModel *baseModel = [BaseModel mj_objectWithKeyValues:responseBody];
        if (baseModel.code != 0)
        {
            [SVProgressHUD showInfoWithStatus:baseModel.msg];
            [SVProgressHUD dismissWithDelay:1];
            return ;
        }
        
        [SVProgressHUD dismiss];
        //请求数据"data"转模型
        KUserLoginModel *userLoginModel = [KUserLoginModel mj_objectWithKeyValues:[responseBody valueForKey:@"data"]];
        
        //JpushHead() + UserId
        NSString *aliasString = [NSString stringWithFormat:@"%@%@",userLoginModel.JpushHead,userLoginModel.UserId];
        [JPUSHService setAlias:aliasString completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
            
            //设置别名成功后，code值为0
            NSLog(@"++++++++rescode: %ld, \ntags: %@, \nalias: %@\n", (long)iResCode, @"tag" , iAlias);
            

        } seq:0];
        
        // TODO: Helen，2018.9.20, 推出登录时做这个清除操作
        /* 在推出登录部分，清除别名，实现推出登录状态获取不到推送消息
        [JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
            
            NSLog(@"rescode: %ld, \ntags: %@, \nalias: %@\n", (long)iResCode, @"tag" , iAlias);
            
        } seq:0];         */
        
        //本地存储账号密码
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        [userDefaults setObject:self.userInputMessage.text forKey:@"userName"];
        [userDefaults setObject:self.passwordInputMessage.text forKey:@"passWord"];

        self.MenuRootVC = [[KMenuRootViewController alloc]init];
        self.MenuRootVC.loginModel = userLoginModel;
        self.MenuRootVC.homePageVC.loginModel = userLoginModel;
        self.MenuRootVC.discoveryVC.loginModel = userLoginModel;
        self.view.window.rootViewController = self.MenuRootVC;
        
    } failureBlock:^(NSString *error) {
        ErrorShow(error);
    }];
    
}

#pragma mark - 微信登陆按钮的点击方法,第一步 -- 初始化微信，传参数
-(void)WechatLoginClick{
    if ([WXApi isWXAppInstalled]) {
        SendAuthReq *req = [[SendAuthReq alloc] init];
        req.scope = @"snsapi_userinfo";
        req.state = @"123";
        [WXApi sendReq:req];
        
        // TODO: Helen，9.14，公众号跳转待加入
//        JumpToBizProfileReq *req = [[JumpToBizProfileReq alloc]init];
//        req.username=@"gh_6b31b722a1e8";
//        req.extMsg = @"";
//        req.profileType =0;
        [WXApi sendReq:req];
    }else{
        //把微信登录的按钮隐藏掉
    }
}

#pragma mark - 第一步 -- 微信登录通知 获取code
- (void)wechatDidLoginNotification:(NSNotification*)notification
{
    NSDictionary* userInfo = [NSDictionary new];
    userInfo = [notification userInfo];
    NSString *code = [userInfo valueForKey:@"code"];
    [self getWechatAccessTokenWithCode:code];
}

#pragma mark - 第二步 -- 根据code获取accessToken和openId
- (void)getWechatAccessTokenWithCode:(NSString *)code
{
    NSString *url =[NSString stringWithFormat:
                    @"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",
                    kAppKey_Wechat,kSecret_Wechat,code];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (data)
            {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data
                                                                    options:NSJSONReadingMutableContainers error:nil];
                
                NSLog(@"%@",dic);
                NSString *accessToken = dic[@"access_token"];
                NSString *openId = dic[@"openid"];
                
                [self getWechatUserInfoWithAccessToken:accessToken openId:openId];
            }
        });
    });
}

#pragma mark - 第三步 -- 根据accessToken和openId获取用户信息
- (void)getWechatUserInfoWithAccessToken:(NSString *)accessToken openId:(NSString *)openId
{
    NSString *url =[NSString stringWithFormat:
                    @"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",accessToken,openId];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (data)
            {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data
                                                                    options:NSJSONReadingMutableContainers error:nil];
                
                NSLog(@"%@",dic);
                
                NSString *wxOpenId = [dic valueForKey:@"openid"]; // openId
                NSString *wxNickName = [dic valueForKey:@"nickname"]; //昵称
                NSString *wxHeadImage = [dic valueForKey:@"headimgurl"]; //头像
                NSString *wxUnionid = [dic valueForKey:@"unionid"]; //微信登录UnionId
                
                [self loginWithWXOpenId:wxOpenId wxNickName:wxNickName wxHeadImage:wxHeadImage wxUnionid:wxUnionid];
            }
        });
    });
}

#pragma mark - 第四步 -- 通过获取到的用户信息登录微信
-(void)loginWithWXOpenId:(NSString *)openId wxNickName:(NSString *)nickName wxHeadImage:(NSString *)headImage wxUnionid:(NSString *)unionid{
    [SVProgressHUD show];
    NSDictionary *parameters = @{
                                 @"_appid" : @"103",
                                 @"_code" : @"",
                                 @"AccountId": openId, //第三方微信用户OpenId
                                 @"UnionId": unionid, //微信登录UnionIdÔ
                                 @"AccountType": @"1", //第三方用户类型（1：微信）
                                 @"NickName": nickName, //昵称
                                 @"HeadPhoto": headImage//头像
                                 };
    
    [[NetworkSingleton sharedManager]POSTdata:parameters Path:@"/common/User/LoginByThird" successBlock:^(id responseBody) {

        BaseModel *baseModel = [BaseModel mj_objectWithKeyValues:responseBody];
        if (baseModel.code != 0)
        {
            [SVProgressHUD showInfoWithStatus:baseModel.msg];
            [SVProgressHUD dismissWithDelay:1];
            return ;
        }
        
        BaseModel *baseModelInside = [BaseModel mj_objectWithKeyValues:baseModel.data];
        //请求数据"data"转模型
        KWXLoginUserListModel *wxUserLoginModel = [KWXLoginUserListModel mj_objectWithKeyValues:baseModelInside.data];
        
        [SVProgressHUD dismiss];
        self.MenuRootVC = [[KMenuRootViewController alloc]init];
        self.MenuRootVC.wxUserModel = wxUserLoginModel;
        self.view.window.rootViewController = self.MenuRootVC;
        
    } failureBlock:^(NSString *error) {
        ErrorShow(error);
    }];
}

#pragma mark 键盘弹出
- (void)keyboardWillShowChangeFrame:(NSNotification*)notification
{
    NSDictionary* info = [notification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    //    NSLog(@"keyboardWillShowChangeFrame info = %@", info);
    if (CGRectGetMinY(self.view.frame) < 0) {
        return;
    }
    //保证最下面的控件不被遮挡
    CGFloat bottomY = ScreenHeight;
    
    if ([UIScreen mainScreen].bounds.size.height == 480 || [UIScreen mainScreen].bounds.size.height ==  568.0f) {
        bottomY = CGRectGetMaxY(self.passwordbgView.frame) - 5;
    }
    
    NSTimeInterval duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        if ([UIScreen mainScreen].bounds.size.height == 480 || [UIScreen mainScreen].bounds.size.height ==  568.0f) {
            self.view.frame = CGRectMake(0, (ScreenHeight - bottomY) - kbSize.height , CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds));
        }else{
            self.view.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
        }
    }];
}

#pragma mark 键盘弹出
- (void)keyboardWillHideChangeFrame:(NSNotification*)notification
{
    NSDictionary* info = [notification userInfo];
    //    NSLog(@"keyboardWillHideChangeFrame info = %@", info);
    NSTimeInterval duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        self.view.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds));
    }];
}

#pragma mark 键盘失去第一响应
- (BOOL)textFieldShouldReturn:(UITextField*)textField
{
    if (textField == self.userInputMessage) {
        [self.userInputMessage resignFirstResponder];
    }
    else if (textField == self.passwordInputMessage) {
        [self.passwordInputMessage resignFirstResponder];
    }
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch*>*)touches withEvent:(UIEvent*)event
{
    [self.view endEditing:YES];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"wechatDidLoginNotification" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UIKeyboardWillShowNotification" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"UIKeyboardWillHideNotification" object:nil];
}

#pragma mark - getter
-(UIImageView *)iconImageView{
    if (!_iconImageView) {
        _iconImageView = [[UIImageView alloc] init];
        _iconImageView.image = [UIImage imageNamed:@"logo"];
    }
    return _iconImageView;
}

-(UITextField *)userInputMessage{
    if (!_userInputMessage) {
        _userInputMessage = [[UITextField alloc] init];
        _userInputMessage.textColor = [UIColor colorWithRed:63.0f/255.0f green:63.0f/255.0f blue:63.0f/255.0f alpha:1.0f];
        _userInputMessage.font = [UIFont systemFontOfSize:17];
        _userInputMessage.placeholder = @"用户名/手机号";
        _userInputMessage.delegate = self;
        [_userInputMessage setValue:[UIColor colorWithRed:189.0f/255.0f green:189.0f/255.0f blue:189.0f/255.0f alpha:1.0f] forKeyPath:@"_placeholderLabel.textColor"];
        [_userInputMessage setValue:[UIFont boldSystemFontOfSize:17] forKeyPath:@"_placeholderLabel.font"];
    }
    return _userInputMessage;
}

-(UIImageView *)userNamebgView{
    if (!_userNamebgView) {
        _userNamebgView = [[UIImageView alloc] init];
        _userNamebgView.image = [UIImage imageNamed:@"yonghuming"];
    }
    return _userNamebgView;
}

-(UITextField *)passwordInputMessage{
    if (!_passwordInputMessage) {
        _passwordInputMessage = [[UITextField alloc] init];
        _passwordInputMessage.textColor = [UIColor colorWithRed:63.0f/255.0f green:63.0f/255.0f blue:63.0f/255.0f alpha:1.0f];
        _passwordInputMessage.font = [UIFont systemFontOfSize:17];
        _passwordInputMessage.placeholder = @"请输入密码";
        _passwordInputMessage.delegate = self;
        _passwordInputMessage.secureTextEntry = YES;
        [_passwordInputMessage setValue:[UIColor colorWithRed:189.0f/255.0f green:189.0f/255.0f blue:189.0f/255.0f alpha:1.0f] forKeyPath:@"_placeholderLabel.textColor"];
        [_passwordInputMessage setValue:[UIFont boldSystemFontOfSize:17] forKeyPath:@"_placeholderLabel.font"];
    }
    return _passwordInputMessage;
}

-(UIImageView *)passwordbgView{
    if (!_passwordbgView) {
        _passwordbgView = [[UIImageView alloc] init];
        _passwordbgView.image = [UIImage imageNamed:@"mima"];
    }
    return _passwordbgView;
}

-(UIView *)line1{
    if (!_line1) {
        _line1 = [[UIView alloc] init];
        _line1.backgroundColor = [UIColor colorWithRed:204.0f/255.0f green:204.0f/255.0f blue:204.0f/255.0f alpha:1.0f];
    }
    return _line1;
}

-(UILabel *)orAppLoginLabel{
    if (!_orAppLoginLabel) {
        _orAppLoginLabel = [[UILabel alloc] init];
        _orAppLoginLabel.text = @"Or";
        _orAppLoginLabel.font = [UIFont systemFontOfSize:17];
        _orAppLoginLabel.textColor = [UIColor colorWithRed:204.0f/255.0f green:204.0f/255.0f blue:204.0f/255.0f alpha:1.0f];
    }
    return _orAppLoginLabel;
}

-(UIView *)line2{
    if (!_line2) {
        _line2 = [[UIView alloc] init];
        _line2.backgroundColor = [UIColor colorWithRed:204.0f/255.0f green:204.0f/255.0f blue:204.0f/255.0f alpha:1.0f];
    }
    return _line2;
}

-(UIButton *)loginButton{
    if (!_loginButton) {
        _loginButton = [[UIButton alloc] init];
        [_loginButton setBackgroundImage:[UIImage imageNamed:@"sign in_button"] forState:UIControlStateNormal];
    }
    return _loginButton;
}

- (UIButton *)WechatLoginBtn{
    if (!_WechatLoginBtn) {
        _WechatLoginBtn = [[UIButton alloc] init];
        
        [_WechatLoginBtn setBackgroundImage:[UIImage imageNamed:@"weixin_button"] forState:UIControlStateNormal];
        [_WechatLoginBtn addTarget:self action:@selector(WechatLoginClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _WechatLoginBtn;
}

@end
